package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import springfox.documentation.spring.web.json.Json;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderDetailMapper orderDetailMapper;
    @Autowired
    AddressBookMapper addressBookMapper;
    @Autowired
    ShoppingCartMapper shoppingCartMapper;
    @Autowired
    DishMapper dishMapper;
    @Autowired
    SetmealMapper setmealMapper;
    @Autowired
    WebSocketServer webSocketServer;

    /**
     * 用户下单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //判断有没有地址簿数据,有就抛异常
        Long addressBookId = ordersSubmitDTO.getAddressBookId();
        AddressBook addressBook = addressBookMapper.getById(addressBookId);
        addressBook.getId();
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //判断购物车有没有数据,有就抛异常
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        //根据用户id拿到购物车数据
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //添加订单表数据

        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setPhone(addressBook.getPhone());
        orders.setPayStatus(0);
        orders.setUserId(userId);
        orders.setStatus(1);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setOrderTime(LocalDateTime.now());
        orders.setConsignee(addressBook.getConsignee());
        orders.setAddress(addressBook.getDetail());
        orderMapper.insert(orders);
        // orderDetailMapper.getAmountById(orders.getId());
        //添加订单明细表
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        orderDetailMapper.insert(orderDetailList);
        //清空购物车
        shoppingCartMapper.deleteByUserId(userId);
        //返回数据
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setId(orders.getId());
        orderSubmitVO.setOrderNumber(orders.getNumber());
        orderSubmitVO.setOrderAmount(orders.getAmount());
        orderSubmitVO.setOrderTime(orders.getOrderTime());
        return orderSubmitVO;
    }

    /**
     * 用户端历史订单查询
     *
     * @return
     */
    @Transactional
    public PageResult historicalOrderQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        //分页条件查询
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);
        List<OrderVO> list = new ArrayList<>();
        //遍历订单数据
        for (Orders orders : page) {
            Long orderId = orders.getId();
            List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orderId);
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders, orderVO);
            orderVO.setOrderDetailList(orderDetailList);
            list.add(orderVO);
        }
        return new PageResult(page.getTotal(), list);
    }

    /**
     * 用户端查询订单详情
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO orderDetails(Long id) {
        Orders orders = orderMapper.getById(id);
        List<OrderDetail> list = orderDetailMapper.getByOrderId(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(list);
        return orderVO;
    }

    /**
     * 取消订单
     *
     * @param id
     */
    @Override
    public void cancel(Long id) {
        Orders orders = orderMapper.getById(id);
        Integer status = orders.getStatus();
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);

        } else {
            if (status > 2) {
                throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
            }

            Orders orders1 = new Orders();
            orders1.setId(orders.getId());
            orders1.setStatus(Orders.CANCELLED);
            orderMapper.updateOrderStatus(orders1);
        }

    }

    /**
     * 再来一单
     *
     * @param id
     */
    @Override
    public void repetition(Long id) {
        ShoppingCart shoppingCart = new ShoppingCart();
        //根据订单id查询订单明细表数据
        List<OrderDetail> list = orderDetailMapper.getByOrderId(id);
        //遍历
        for (OrderDetail orderDetail : list) {
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            shoppingCart.setUserId(BaseContext.getCurrentId());
            //插入数据
            shoppingCartMapper.insert(shoppingCart);
        }
    }

    /**
     * 管理端订单搜索
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);
//        List<Orders> result = page.getResult();
        List<OrderVO> list = new ArrayList<>();

        String orderDishes = "";
        for (Orders orders : page) {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders, orderVO);
            Long ordersId = orders.getId();
            List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(ordersId);
            orderVO.setOrderDetailList(orderDetailList);
            for (OrderDetail detail : orderDetailList) {
                orderDishes += detail.getName() + "*" + detail.getNumber() + ";";
            }
            orderVO.setOrderDishes(orderDishes);
            list.add(orderVO);
        }

        return new PageResult(page.getTotal(), list);
    }

    /**
     * 老师代码
     */
//        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
//
//        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);
//
//        // 部分订单状态，需要额外返回订单菜品信息，将Orders转化为OrderVO
//        List<OrderVO> orderVOList = getOrderVOList(page);
//
//        return new PageResult(page.getTotal(), orderVOList);
//    }
//    private List<OrderVO> getOrderVOList(Page<Orders> page) {
//        // 需要返回订单菜品信息，自定义OrderVO响应结果
//        List<OrderVO> orderVOList = new ArrayList<>();
//
//        List<Orders> ordersList = page.getResult();
//        if (!CollectionUtils.isEmpty(ordersList)) {
//            for (Orders orders : ordersList) {
//                // 将共同字段复制到OrderVO
//                OrderVO orderVO = new OrderVO();
//                BeanUtils.copyProperties(orders, orderVO);
//                String orderDishes = getOrderDishesStr(orders);
//
//                // 将订单菜品信息封装到orderVO中，并添加到orderVOList
//                orderVO.setOrderDishes(orderDishes);
//                orderVOList.add(orderVO);
//            }
//        }
//        return orderVOList;
//    }
//    /**
//     * 根据订单id获取菜品信息字符串
//     *
//     * @param orders
//     * @return
//     */
//    private String getOrderDishesStr(Orders orders) {
//        // 查询订单菜品详情信息（订单中的菜品和数量）
//        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());
//
//        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
//        List<String> orderDishList = orderDetailList.stream().map(x -> {
//            String orderDish = x.getName() + "*" + x.getNumber() + ";";
//            return orderDish;
//        }).collect(Collectors.toList());
//
//        // 将该订单对应的所有菜品信息拼接在一起
//        return String.join("", orderDishList);
//    }


    /**
     * 管理端各个状态的订单数量统计
     *
     * @return
     */

    public OrderStatisticsVO statistics() {
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(0);
        orderStatisticsVO.setConfirmed(0);
        orderStatisticsVO.setDeliveryInProgress(0);
        List<Orders> orders = orderMapper.selectOrder();
        for (Orders order : orders) {
            Integer status = order.getStatus();
            if (status == 2) {
                orderStatisticsVO.setToBeConfirmed(orderStatisticsVO.getToBeConfirmed() + 1);
            } else if (status == 3) {
                orderStatisticsVO.setConfirmed(orderStatisticsVO.getConfirmed() + 1);
            } else if (status == 4) {
                orderStatisticsVO.setDeliveryInProgress(orderStatisticsVO.getDeliveryInProgress() + 1);
            }
        }

        return orderStatisticsVO;
    }

    /**
     * 管理端查询订单详情
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO orderDetails1(Long id) {
        OrderVO orderVO = new OrderVO();
        List<OrderDetail> list = orderDetailMapper.getByOrderId(id);
        Orders orders = orderMapper.getById(id);
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(list);
        return orderVO;
    }

    /**
     * 管理端接单
     *
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = new Orders();
        orders.setStatus(Orders.CONFIRMED);
        orders.setId(ordersConfirmDTO.getId());
        orderMapper.updateOrderStatus(orders);
    }

    /**
     * 管理端拒单
     *
     * @param ordersRejectionDTO
     * @return
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orders = new Orders();
        orders.setStatus(6);
        BeanUtils.copyProperties(ordersRejectionDTO, orders);
        orderMapper.updateOrderStatus(orders);
    }

    /**
     * 管理端取消订单
     *
     * @param ordersCancelDTO
     */
    @Override
    public void cancel1(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = new Orders();
        orders.setStatus(6);
        orders.setCancelTime(LocalDateTime.now());
        BeanUtils.copyProperties(ordersCancelDTO, orders);
        orderMapper.updateOrderStatus(orders);
    }

    /**
     * 管理端派送订单
     *
     * @param id
     */
    @Override
    public void delivery(Long id) {
        Orders order = new Orders();
        Orders orders = orderMapper.getById(id);
        order.setStatus(4);
        order.setId(orders.getId());
        orderMapper.updateOrderStatus(order);
    }

    /**
     * 管理端完成订单
     *
     * @param id
     */
    @Override
    public void complete(Long id) {
        Orders order = new Orders();
        Orders orders = orderMapper.getById(id);
        order.setStatus(5);
        order.setId(orders.getId());
        orderMapper.updateOrderStatus(order);
    }

    /**
     * 订单支付
     */
    @Override
    public void payment(OrdersPaymentDTO ordersPaymentDTO) {
        Orders orders = new Orders();
        String number = ordersPaymentDTO.getOrderNumber();
        Integer payMethod = ordersPaymentDTO.getPayMethod();
        orders.setPayMethod(payMethod);
        orders.setNumber(number);
        orders.setPayStatus(1);
        orderMapper.updateOrderStatus(orders);
        Map map = new HashMap();
        map.put("type", 1);
        map.put("orderId", orders.getId());
        map.put("content", "订单号" + number);
        webSocketServer.sendToAllClient(JSON.toJSONString(map));

    }

    /**
     * 催单接口
     *
     * @param id
     */
    @Override
    public void reminder(Long id) {
        Orders orders = orderMapper.getById(id);
        Long ordersId = orders.getId();
        String number = orders.getNumber();
        Map map = new HashMap();
        map.put("type", 2);
        map.put("orderId", ordersId);
        map.put("content", "订单号" + number);
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }
}
